<?php

namespace App\Http\Controllers\Guard\Advert;

use App\Http\Controllers\Common\GuardController;
use App\Models\Advert\Advert;
use App\Models\Advert\AdvertChannel;
use App\Models\Constant\Constant;
use Illuminate\Http\Request;

class AdvertController extends GuardController {

    public function lst(Request $request) {
        $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
        $page  = $request->input('page',1);
        $conditions = $request->input();
        $records = (new Advert())->getLst($conditions)->paginate($pageSize,$this->getCol,'page',$page);

        $mapAdvertChannel = (new AdvertChannel())->getLst()->get(['id as value','name as label']);
        $mapTemp = $mapAdvertChannel->pluck('label','value')->toArray();
        foreach ($records as $record) {
            $record->channel_name = $mapTemp[$record->channel_id]??'未知';;
        }
        return responseSuccess($records->items(),$records->total(),100000,['map_advert_channel_type'=>$mapAdvertChannel]);
    }

    public function change(Request $request) {
        $ids = $request->input('ids',[]);
        if($request->has('status')){
            $status = $request->input('status');
            return $this->changeColByIds(Advert::class, $ids, compact('status'));
        }

        if($request->has('is_top')){
            $is_top = $request->input('is_top');
            return $this->changeColByIds(Advert::class, $ids, compact('is_top'));
        }

        return responseSuccess();

    }

    public function add(Request $request) {
        $id = $request->input('id',0);
        $info = $request->input();

        $this->validate($request, [
            'res_url'=>'required',
            'channel_id'=>'required',
        ],[],[
            'res_url'=>'图片或视频',
            'channel_id'=>'频道'
        ]);

        if(isset($info['channel_id']) && is_array($info['channel_id'])){
            $info['channel_id'] = array_pop($info['channel_id']);
        }

        Advert::updateOrCreate(compact('id'),$info);
        return responseSuccess();
    }

    public function detail(Request $request) {
        $ids = $request->input('ids',[]);
        return $this->getRecordByIds(Advert::class, $ids);
    }

    public function del(Request $request) {
        $ids = $request->input('ids',[]);
        return $this->delRecords(Advert::class, $ids);
    }

}
